package cn.wowjoy.office.pm.view.viewodel;

import android.arch.lifecycle.MediatorLiveData;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.response.StaffResponse;
import cn.wowjoy.office.pm.data.CardResponse;
import cn.wowjoy.office.pm.data.PmProjectResponse;
import cn.wowjoy.office.pm.data.PmReportDetailResponse;
import cn.wowjoy.office.pm.data.SubmitResponse;
import cn.wowjoy.office.pm.data.request.PmReportDetailSubmit;
import cn.wowjoy.office.pm.db.PmListDao;
import cn.wowjoy.office.pm.db.PmListDetailDao;
import cn.wowjoy.office.pm.db.PmReportListDetailEntity;
import cn.wowjoy.office.pm.db.PmReportListEntity;
import cn.wowjoy.office.utils.PreferenceManager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;

public class PmReportDetailViewModel extends NewBaseViewModel {
    @Inject
    public PmReportDetailViewModel(@NonNull NewMainApplication application) {
        super(application);
    }

    @Override
    public void onCreateViewModel() {

    }
    @Inject
    ApiService apiService;

    public MediatorLiveData<LiveDataWrapper<CardResponse>> cardDetail = new MediatorLiveData<>();
    public void getCardData(String id){
        cardDetail.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getCardData(id)
                .flatMap(new ResultDataParse<CardResponse>())
                .compose(new RxSchedulerTransformer<CardResponse>())
                .subscribe(new Consumer<CardResponse>() {
                    @Override
                    public void accept(CardResponse taskListResponse) throws Exception {
                        cardDetail.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        cardDetail.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }
    public MediatorLiveData<LiveDataWrapper<PmProjectResponse>> pmProjectLook = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<PmProjectResponse>> pmProjectElec = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<PmProjectResponse>> pmProjectFunction = new MediatorLiveData<>();
    public void getPmProject(String id,int type){
        switch (type){
            case 100:
                pmProjectElec.setValue(LiveDataWrapper.loading(null));
                break;
            case 200:
                pmProjectLook.setValue(LiveDataWrapper.loading(null));
                break;
            case 300:
                pmProjectFunction.setValue(LiveDataWrapper.loading(null));
                break;
        }

        Disposable disposable = apiService.getPmProject(id)
                .flatMap(new ResultDataParse<PmProjectResponse>())
                .compose(new RxSchedulerTransformer<PmProjectResponse>())
                .subscribe(new Consumer<PmProjectResponse>() {
                    @Override
                    public void accept(PmProjectResponse taskListResponse) throws Exception {
                        switch (type){
                            case 100:
                                pmProjectElec.setValue(LiveDataWrapper.success(taskListResponse));
                                break;
                            case 200:
                                pmProjectLook.setValue(LiveDataWrapper.success(taskListResponse));
                                break;
                            case 300:
                                pmProjectFunction.setValue(LiveDataWrapper.success(taskListResponse));
                                break;
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        switch (type){
                            case 100:
                                pmProjectElec.setValue(LiveDataWrapper.error(throwable,null));
                                break;
                            case 200:
                                pmProjectLook.setValue(LiveDataWrapper.error(throwable,null));
                                break;
                            case 300:
                                pmProjectFunction.setValue(LiveDataWrapper.error(throwable,null));
                                break;
                        }
                    }
                });
        addDisposable(disposable);
    }
    /**
     *  提交表单数据到服务器
     */
    public MediatorLiveData<LiveDataWrapper<SubmitResponse>> submit = new MediatorLiveData<>();
    public void submitPmReport(PmReportDetailSubmit body,String uuid){
        submit.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.submitPmReport(body,uuid)
                .flatMap(new ResultDataParse<SubmitResponse>())
                .compose(new RxSchedulerTransformer<SubmitResponse>())
                .subscribe(new Consumer<SubmitResponse>() {
                    @Override
                    public void accept(SubmitResponse taskListResponse) throws Exception {
                        submit.setValue(LiveDataWrapper.success(taskListResponse));
                        getAsyData().execute(body);
//                        StaffResponse  userInfo = new Gson().fromJson(PreferenceManager.getInstance().getStuffInfo(), StaffResponse.class);
//                        List<PmReportListDetailEntity> pmReportListDetailEntities = mDetailDao.queryExist(body.getCardId(),userInfo.getStaffName());
//                        if(null != pmReportListDetailEntities && pmReportListDetailEntities.size()>0){
//                            mDetailDao.deleteByQRCode(body.getCardId(), userInfo.getStaffName());
//                            mPmListDao.deleteByQRCode(body.getCardId(), userInfo.getStaffName());
//                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        submit.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }
    public MediatorLiveData<LiveDataWrapper<SubmitResponse>> save = new MediatorLiveData<>();
    public void savePmReport(PmReportDetailSubmit body,String uuid){
        save.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.savePmReport(body,uuid)
                .flatMap(new ResultDataParse<SubmitResponse>())
                .compose(new RxSchedulerTransformer<SubmitResponse>())
                .subscribe(new Consumer<SubmitResponse>() {
                    @Override
                    public void accept(SubmitResponse taskListResponse) throws Exception {
                        save.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        save.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }
    public MediatorLiveData<LiveDataWrapper<PmReportDetailResponse>> localSave = new MediatorLiveData<>();
    public void check(PmReportDetailResponse model,boolean isReplace,String qrCodeOld){
        localSave.setValue(LiveDataWrapper.loading(null));
        Disposable observer = (Disposable) Observable.create(new ObservableOnSubscribe<PmReportListDetailEntity>() {
            @Override
            public void subscribe(ObservableEmitter<PmReportListDetailEntity> e) throws Exception {
                PmReportDetailResponse.PmReportVO pmReportVO = model.getPmReportVO();
                List<PmReportListDetailEntity> pmReportListDetailEntities = mDetailDao.queryExist(qrCodeOld, model.getPmReportVO().getPmUserName());
                if(null != pmReportListDetailEntities && pmReportListDetailEntities.size()>0){
                    //说明数据库存在这条 要更新   因为有替换工作  有替换就先删除再加    没有就直接跟新
                    if(isReplace){
                        mDetailDao.deleteByQRCode(qrCodeOld, pmReportVO.getPmUserName());
                        mPmListDao.deleteByQRCode(qrCodeOld, pmReportVO.getPmUserName());
                        addDateBase(model);
                    }else{
                        mDetailDao.updateExist(new Gson().toJson(model),pmReportVO.getQrCode(),pmReportVO.getPmUserName() );
                        mPmListDao.updateExist(TextUtils.isEmpty(pmReportVO.getOffLineRemark())?"":pmReportVO.getOffLineRemark(),TextUtils.isEmpty(pmReportVO.getPmDate())?"":pmReportVO.getPmDate(),new Date().getTime(),
                                pmReportVO.getCardName(), pmReportVO.getCardDeptName(),
                                pmReportVO.getQrCode(),pmReportVO.getPmUserName());
                    }
                }else{
                    addDateBase(model);
                }
                 e.onComplete();
            }
        }).compose(new RxSchedulerTransformer<>())
                .subscribeWith(new DisposableObserver<PmReportListDetailEntity>() {
                    @Override
                    public void onNext(PmReportListDetailEntity o) {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        localSave.setValue(LiveDataWrapper.success(model));
                    }
                });
        addDisposable(observer);
    }
    public void addDateBase(PmReportDetailResponse model){
        PmReportDetailResponse.PmReportVO pmReportVO = model.getPmReportVO();
        PmReportListDetailEntity entity = new PmReportListDetailEntity();
        entity.setJsonEntity(new Gson().toJson(model));
        entity.setQrCode(pmReportVO.getQrCode());
        entity.setUserName(pmReportVO.getPmUserName());
        mDetailDao.saveEntity(entity);
        PmReportListEntity reportListEntity = new PmReportListEntity();
        reportListEntity.setQrCode(pmReportVO.getQrCode());
        reportListEntity.setUserName(pmReportVO.getPmUserName());
        if(!TextUtils.isEmpty(pmReportVO.getOffLineRemark())){
            reportListEntity.setRemarks(pmReportVO.getOffLineRemark());
        }
        if(!TextUtils.isEmpty(pmReportVO.getPmDate())){
            reportListEntity.setPmDate(pmReportVO.getPmDate());
        }
        //设备名称
        if(!TextUtils.isEmpty(pmReportVO.getCardName())){
            reportListEntity.setCardName(pmReportVO.getCardName());
        }
        //所在科室
        if(!TextUtils.isEmpty(pmReportVO.getCardDeptName())){
            reportListEntity.setCardDeptName(pmReportVO.getCardDeptName());
        }
        reportListEntity.setLocal(true);
        reportListEntity.setUpdateTime(new Date().getTime());
        Log.e("PXY", "addDateBase: "+ new Date().getTime());
        reportListEntity.setBillStatusName("待完善");
        reportListEntity.setCheckResultName(TextUtils.isEmpty(pmReportVO.getCheckResultName())?"待完善":pmReportVO.getCheckResultName());
        mPmListDao.saveEntity(reportListEntity);
    }
    @Inject
    PmListDetailDao mDetailDao;
    @Inject
    PmListDao mPmListDao;
    private AsyData mAsyData;
    public AsyData getAsyData(){
        if(null == mAsyData)
            mAsyData = new AsyData(mPmListDao,mDetailDao);
        return mAsyData;
    }
    public static class AsyData extends AsyncTask<PmReportDetailSubmit,Void ,Void > {
        private PmListDetailDao mDetailDao;
        private PmListDao mPmListDao;

        public AsyData(PmListDao mPmListDao,PmListDetailDao detailDao) {
            this.mPmListDao = mPmListDao;
            mDetailDao = detailDao;
        }

        @Override
        protected Void doInBackground(PmReportDetailSubmit... submitResponses) {
            PmReportDetailSubmit body = submitResponses[0];
            StaffResponse  userInfo = new Gson().fromJson(PreferenceManager.getInstance().getStuffInfo(), StaffResponse.class);
            List<PmReportListDetailEntity> pmReportListDetailEntities = mDetailDao.queryExist(body.getQrCodeOld(),userInfo.getStaffName());
            if(null != pmReportListDetailEntities && pmReportListDetailEntities.size()>0){
                mDetailDao.deleteByQRCode(body.getQrCodeOld(), userInfo.getStaffName());
                mPmListDao.deleteByQRCode(body.getQrCodeOld(), userInfo.getStaffName());
            }
            return null;
        }
    }


}
